const Router = require('koa-router')
const execSQL = require('../db/index')
const {formatHumpLineTransfer, formatToLine} = require('../utils/index')

const router = new Router()
//获取商品
router.get('/getGoods', async (ctx) => {
  const {pageNum = 1,pageSize = 10,...filter} = ctx.query
  const keys = Object.keys(filter).filter(item => !!filter[item])
  let whereSql = keys.length===0?'':' WHERE '
  keys.forEach((item, i) => {
    if(filter[item])
      whereSql += `${i===0?'':' AND '}${formatToLine(item)} = '${filter[item]}'`
  })
  console.log(whereSql)
  const [{total}] = await execSQL('SELECT COUNT(*) as total FROM goods' + whereSql)
  let start = (pageNum-1)*pageSize
  let end = pageNum * pageSize
  // if(end>total) {
  //   end = total
  // }
  const data = await execSQL(`SELECT * FROM goods${whereSql} LIMIT ${start},${end}`)
  const list = data.map(item => {
    return formatHumpLineTransfer(item)
  })
  ctx.body = {
    code: 200,
    data:{
      list,
      total
    }
  }
});
router.post('/addGoods', async (ctx) => {
  
})
module.exports = router